package com.heqiang.web.servlet;


import com.heqiang.domain.Asign;
import com.heqiang.service.UserService;
import com.heqiang.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取参数,调用方法
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String verifycode = request.getParameter("verifycode");
        //获取系统验证码
        HttpSession session = request.getSession();
        StringBuffer checkCode = (StringBuffer) session.getAttribute("checkCode");
        if (!checkCode.toString().equalsIgnoreCase(verifycode)) {
            //验证码错误
            request.setAttribute("login_msg", "验证码错误,请重新输入!");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } else {
            //验证码正确,获取参数,封装对象,调用方法,返回对象
            //1.成功 保存数据在域中,重定向到index界面
            //2.失败 保存数据到域中,转发到index界面
            Map<String, String[]> map = request.getParameterMap();
            Asign asign = new Asign();
            try {
                BeanUtils.populate(asign, map);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            UserServiceImpl userService = new UserServiceImpl();
            Asign as = userService.login(asign);
            if (as != null) {
                //登陆成功
                session.setAttribute("asign", as);
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            } else {
                //登陆失败
                request.setAttribute("login_msg", "用户名或密码有误!");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
